class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution(object):
    def swapNodes(self, head, k):
        node = head
        t = 0
        while node:
            t += 1
            node = node.next
        node = head
        c = 0
        while node:
            c += 1
            if c == k:
                node1 = node
            if c == t + 1 - k:
                node2 = node
            node = node.next
        node1.val, node2.val = node2.val, node1.val
        return head


